package com.sti.platform.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.aisino.core.server.BaseService;
import com.aisino.tools.util.DateUtils;
import com.sti.platform.dao.UserDao;
import com.sti.platform.model.Company;
import com.sti.platform.model.User;
import com.sti.platform.model.UserGroup;
import com.sti.platform.model.UserRole;
import com.sti.platform.service.UserService;
import com.sti.platform.util.excel.UtilExcel;

@Service
public class UserServiceImpl extends BaseService implements UserService {

	@Autowired
	private UserDao userDao;
	

	@Override
	public void updateUser(User user,List<String> roles) {
		user.setXgr("admin");
		user.setXgrId("admin123");
		user.setXgsj(DateUtils.format(new Date()));
		super.update(user);
		List<UserRole> list = userDao.queryRole(user.getId());
		for(UserRole userRole :list){
			String id = userRole.getId();
			super.remove(UserRole.class,id);		
		}
		for(String id : roles){
			UserRole role = new UserRole();
			role.setUserId(user.getId());
			role.setRoleId(id);
			super.update(role);
		}
	}
	
	@Override
	public void delectUser(String userId) {
		super.remove(User.class, userId);
		//删除用户组和角色关联连表
		List<UserRole> list = userDao.queryRole(userId);
		if(list.size()>0){
			for(UserRole li :list){
				super.remove(UserRole.class,li.getId());
			}
		}
		List<UserGroup> list2 = userDao.queryGroup(userId);
		if(list2.size()>0){
			for(UserGroup li :list2){
				super.remove(UserGroup.class,li.getId());
			}
		}
	}
	
	@Override
	public void delectUsers(String userIds){
		List<String> userId = Arrays.asList(userIds.split(","));
		for(String user : userId){
			this.delectUser(user);
		}
	}


	@Override
	public void addUser(User user,List<String> roles) {
		user.setCjr("admin");
		user.setCjrId("admin123");
		user.setCjsj(DateUtils.format(new Date()));
		super.save(user);
		if(roles.size() > 0 ){
			for(String id:roles){
				UserRole role = new UserRole();
				role.setUserId(user.getId());
				role.setRoleId(id);
				super.save(role);
			}
		}

	}

	@Override
	public List<User> queryUsersByCondition(String condition,Integer page,Integer row) {
		if(page==null || page==0){//当前页数
			page=1;
		}
		if(row==null || row==0){//每页多少条
			row=10;
		}
		List<User> users = userDao.queryUsersByCondition(condition,page,row);
		return users;
	}

	@Override
	public Map<String,Object> queryUserInfo(String userId) {
		Map<String,Object> user = userDao.queryUserInfo(userId);
		List<Map<String,Object>> roles = userDao.queryRole();
		String roleId = MapUtils.getString(user, "ROLEID");
		if(roleId != null){
			List<String> list = Arrays.asList(roleId.split(","));
			for(Map<String,Object> role: roles){
				String id = MapUtils.getString(role, "ID");
				for(String li : list){
					if(id.equals(li)){
						role.put("checked", "checked");
					}
				}
			}
		}
		user.put("role", roles);
		return user;
	}
	
	@Override
	public Map<String,Object> queryAddInfo(){
		Map<String,Object> map = new HashMap<String,Object>();
		/**
		 * ①查询单位列表
		 * ②查询角色列表
		 * ③查询用户组列表
		 */
		List<Company> compants = userDao.queryCompany();
		List<Map<String,Object>> roles = userDao.queryRole();
		List<Map<String,Object>> groups = userDao.queryGroup();
		map.put("compant", compants);
		map.put("role", roles);
		map.put("group", groups);
		return map;
	}

	@Override
	public List<User> queryUserList(String params) {
		StringBuilder builder = new StringBuilder();
		builder.append("select u.*,t.name as \"company\" from sys_user u left join sys_company t on u.company_id = t.id ");
		if(params != null&&!"".equals(params)){
			String sql = " where u.user_name like '%"+params+"%' or u.major like '%"+params+"%' or u.real_name like '%"+params+"%'";
			builder.append(sql);
		}
		return userDao.queryUser(builder.toString());
	}

	@Override
	public List<User> queryUserList(List<String> userIds) {
		List<User> list = new ArrayList<>();
		for(String user:userIds){
			String sql = "select u.*,t.name as \"company\" from sys_user u left join sys_company t on u.company_id = t.id ";
			sql = sql + " where u.id = '" + user+"'";
			list.addAll(userDao.queryUser(sql));
		}
		return list;
	}

	@Override
	public void eportUser(HttpServletResponse response) {
		UtilExcel<User> ue = new UtilExcel(User.class);
		String sql = "SELECT u.*,GROUP_CONCAT(r.name) AS \"role\",c.name AS \"company\""
				+ " FROM sys_user u "
				+ " LEFT JOIN sys_user_role ur ON u.id = ur.user_id "
				+ " LEFT JOIN sys_role r ON ur.role_id = r.id "
				+ " LEFT JOIN sys_company c ON u.company_id = c.id"
				+ "  GROUP BY u.user_name";
		List<User> list = userDao.queryUser(sql);
		if(!list.isEmpty()){
			ue.getListToExcel(list,"用户列表","用户列表",response);
		}
	}

	@Override
	public void importUser(MultipartFile file) {
		//转换成输入流
		try {
			InputStream is = file.getInputStream();
			UtilExcel<User> ue = new UtilExcel(User.class);
			List<User> list = new ArrayList<User>();
			list = ue.getExcelToList(file);
			System.out.println(list);
			//TODO:将用户数据保存到数据库
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
